/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.brainstretch.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContext;

/**
 *
 * @author mrodaitis
 */
public class FileStorageUtil {
    
    private static final Pattern extensionPattern = Pattern.compile("^((.+))\\.(.+)$");
    
    public static String saveFile(ServletContext context, long quizId, String fileName, byte[] content) throws IOException{
        fileName = fileName.trim();
        if(!isValidFileName(fileName)){
            throw new IllegalArgumentException("Invalid file name");
        }
        String resultName = fileName;        
        System.out.println(context.getRealPath("//WEB-INF//files//"+quizId+"/"+fileName));
        int currentAppend = 0;
        File file = null;
        do{
            file = new File(context.getRealPath("//WEB-INF//files//"+quizId+"/"+resultName));
            resultName = appendNumberTo(fileName, ++currentAppend);
        }while(file.exists());
        
        System.out.println(file.getPath());
        File parentDir = new File(context.getRealPath("//WEB-INF//files//"+quizId+"/"));
        parentDir.mkdirs();
        file.createNewFile();
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(content);
        outputStream.flush();
        outputStream.close();
        
        
        return file.getName();
    }
    
    static boolean isValidFileName(String fileName){
        return extensionPattern.matcher(fileName).matches();
    }
    
    public static String getFileExtension(String fileName){
        if(!isValidFileName(fileName)){
            throw new IllegalArgumentException("Invalid file name");
        }
        Matcher matcher = extensionPattern.matcher(fileName);
        matcher.find();
        return matcher.group(3);
    }
    
    public static String appendNumberTo(String takenFilePath, int num){
        Matcher matcher = extensionPattern.matcher(takenFilePath);
        matcher.find();
        String name = matcher.group(1).toString();
        String ext= matcher.group(3);
        return name+"_"+num+"."+ext;
    }
    
    
}
